package com.enjoyread.core.manager.impl;

import com.enjoyread.core.entity.OssLog;
import com.enjoyread.core.manager.intf.AliOssService;
import com.enjoyread.core.service.intf.OssLogService;
import com.enjoyread.core.service.intf.UserDetailService;
import com.enjoyread.core.utils.AliOssUtils;
import com.enjoyread.common.config.SystemConfig;
import com.enjoyread.common.utils.DateUtil;
import com.enjoyread.common.utils.FileUtils;
import com.enjoyread.common.utils.RUtils;
import com.enjoyread.common.utils.StringUtils;
import com.enjoyread.common.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class AliOssServiceImpl implements AliOssService {
    @Autowired
    private OssLogService service;
    @Autowired
    private UserDetailService detailService;

    @Transactional
    @Override
    public R uploadHead(int uid,String fn,byte[] data) {
        //1.重命名并验证内容
        fn= FileUtils.rename(fn);
        if(data.length>0){
            //2.上传到阿里云的OSS
            Date cdate=DateUtil.getDateYear(SystemConfig.OSS_URL_TIME);
            String url= AliOssUtils.upload(fn, data,cdate);
            if(StringUtils.isNotEmpty(url)){
                //3.新增数据库
                OssLog log=new OssLog(SystemConfig.OSS_TYPE_HEAD,AliOssUtils.bucketName,fn,url,cdate,new Date());
                service.save(log);
                //4.更新头像
                detailService.updateHead(uid,url);
                //4.返回
                return RUtils.ok("ok",url);
            }
        }
        return RUtils.fail("网络异常，上传失败！");
    }
}
